package com.cloud.school.bus.teacherhelper.modules.home;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.android.support.jhf.androidpulltorefresh.library.PullToRefreshBase;
import com.android.support.jhf.androidpulltorefresh.library.PullToRefreshListView;
import com.android.support.jhf.androidpulltorefresh.library.PullToRefreshBase.Mode;
import com.android.support.jhf.dialog.CustomWaitDialog;
import com.android.support.jhf.dialog.CustomWaitDialog.OnKeyCancel;
import com.android.support.jhf.handlerui.HandlerPostUI;
import com.cloud.school.bus.teacherhelper.R;
import com.cloud.school.bus.teacherhelper.base.camera.CacheService;
import com.cloud.school.bus.teacherhelper.base.slidingfragment.BaseAboveFragment;
import com.cloud.school.bus.teacherhelper.base.view.TitleNavBarView;
import com.cloud.school.bus.teacherhelper.entitys.HomeMediaFolder;
import com.cloud.school.bus.teacherhelper.entitys.Picture;
import com.cloud.school.bus.teacherhelper.modules.SlidingActivity;
import com.cloud.school.bus.teacherhelper.modules.home.adapter.HomeAdapter;
import com.cloud.school.bus.teacherhelper.modules.home.camera.CustomCameraActivity;
import com.cloud.school.bus.teacherhelper.modules.home.recorder.FFmpegRecorderActivity;
//import com.cloud.school.bus.teacherhelper.modules.uploadlist.uploadutils.UploadUtils;
import com.cloud.school.bus.teacherhelper.modules.uploadlist.uploadutils.UploadFileUtils;

/**
 * 主页
 * 
 * @author lenovo
 * 
 */
public class HomeFragment extends BaseAboveFragment {

	private interface OnRefreshPictureList {

		public void onRefreshPictureList(
				List<HomeMediaFolder> tempHomeMediaFolders);

	}

	private PullToRefreshListView mPullToRefreshListView;
	private HomeAdapter mHomeAdapter;

	private CustomWaitDialog mCustomWaitDialog;

	private List<HomeMediaFolder> mHomeMediaFolders = new ArrayList<HomeMediaFolder>();
	
	private String mAllPhoto;
	private String mAppShoot;
	private String mVideoDraft;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);
		View view = inflater.inflate(R.layout.fragment_home, null);
		setViewData(view);
		return view;
	}

	@Override
	protected void setViewData(final View view) {

		mAllPhoto = getString(R.string.all_photo);
		mAppShoot = getString(R.string.app_shoot);
		mVideoDraft = getString(R.string.video_draft);
		
		mPullToRefreshListView = (PullToRefreshListView) view
				.findViewById(R.id.listView);
		mPullToRefreshListView.setMode(Mode.PULL_FROM_START);

		getPicture(new OnRefreshPictureList() {

			@Override
			public void onRefreshPictureList(
					List<HomeMediaFolder> tempHomeMediaFolders) {
				mHomeMediaFolders.clear();
				mHomeMediaFolders.addAll(tempHomeMediaFolders);
				mHomeAdapter = new HomeAdapter(mParentContext,
						mHomeMediaFolders);
				mPullToRefreshListView.setAdapter(mHomeAdapter);
				hideWaitDialog();
			}
		});

		setTitleNavBar(view);
		setListener(view);

		((SlidingActivity) mParentContext).getClassinfo(new Runnable() {

			@Override
			public void run() {
				setTitleNavBar(view);
			}
		});

		HandlerPostUI.getHandlerPostUI(new Runnable() {

			@Override
			public void run() {
				// 恢复上传文件数据
//				UploadUtils.getUploadUtils().setContext(mParentContext);
//				UploadUtils.getUploadUtils().readUploadFileDB();
//				UploadUtils.getUploadUtils().uploadFileService();
				UploadFileUtils.getUploadUtils().setContext(mParentContext);
				UploadFileUtils.getUploadUtils().readUploadFileDB();
				UploadFileUtils.getUploadUtils().uploadFileService();
			}
		});

	}

	@Override
	protected void setTitleNavBar(View view) {
		TitleNavBarView titleNavBarView = (TitleNavBarView) view
				.findViewById(R.id.titleNavBarView);
		if (null != mApplication.mClassInfo) {
			titleNavBarView.setMessage(mApplication.mClassInfo.classname);
		} else {
			titleNavBarView.setMessage("");
		}
		titleNavBarView.setLeftButtonImageString(R.drawable.btn_menu_xml, "",
				android.R.color.black);
		titleNavBarView.setLeftButtonOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				((SlidingActivity) mParentContext).toggle();
			}
		});
		titleNavBarView.setRightButtonImageString(R.drawable.btn_camera_xml,
				"", android.R.color.black);
		titleNavBarView.setRightButtonOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(mParentContext,
						FFmpegRecorderActivity.class);
				// Intent intent = new Intent(mParentContext,
				// CustomCameraActivity.class);
				startActivity(intent);
			}
		});
	}

	@Override
	protected void setListener(View view) {
		mPullToRefreshListView
				.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						HomeMediaFolder homeMediaFolderAll = (HomeMediaFolder) mHomeAdapter
								.getItem(arg2);
						if (2 == arg2) {
							// 视频草稿箱
							Intent intent = new Intent(mParentContext,
									VideoSelectedActivity.class);
							intent.putExtra("title", homeMediaFolderAll.folder);
							intent.putExtra("Pictures",
									(ArrayList<Picture>) mHomeMediaFolders
											.get(arg2).pictureList);
							intent.putExtra("flag", arg2);
							startActivityForResult(intent, 0);
						} else {
							Intent intent = new Intent(mParentContext,
									PictureSelectedActivity.class);
							intent.putExtra("title", homeMediaFolderAll.folder);
							intent.putExtra("Pictures",
									(ArrayList<Picture>) mHomeMediaFolders
											.get(arg2).pictureList);
							intent.putExtra("flag", arg2);
							startActivityForResult(intent, 0);
						}
					}
				});
		mPullToRefreshListView
				.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {

					@Override
					public void onRefresh(
							PullToRefreshBase<ListView> refreshView) {

						getPicture(new OnRefreshPictureList() {

							@Override
							public void onRefreshPictureList(
									List<HomeMediaFolder> tempHomeMediaFolders) {
								mHomeMediaFolders.clear();
								mHomeMediaFolders.addAll(tempHomeMediaFolders);
								mHomeAdapter.notifyDataSetChanged();
								hideWaitDialog();
								mPullToRefreshListView.onRefreshComplete();
							}
						});
					}
				});
	}

	/** 获取所有照片 */
	private void getPicture(final OnRefreshPictureList refreshPictureList) {
		showWaitDialog(getString(R.string.loading_photo), null);
		new Thread(new Runnable() {

			@Override
			public void run() {
				final List<HomeMediaFolder> tempHomeMediaFolders = new ArrayList<HomeMediaFolder>();

				tempHomeMediaFolders.clear();
				List<Picture> allPictureList = CacheService
						.getImageList(mParentContext);
				HomeMediaFolder homeMediaFolderAll = new HomeMediaFolder();
				homeMediaFolderAll.folder = mAllPhoto;
				if (null != allPictureList && 0 != allPictureList.size()) {
					homeMediaFolderAll.mediaPath = allPictureList.get(0)
							.getPicturePath();
				} else {
					homeMediaFolderAll.mediaPath = "";
					homeMediaFolderAll.defaultImage = R.drawable.ic_default_album;
				}
				tempHomeMediaFolders.add(homeMediaFolderAll);
				homeMediaFolderAll.pictureList = allPictureList;

				HomeMediaFolder homeMediaFolderCamera = new HomeMediaFolder();
				homeMediaFolderCamera.folder = mAppShoot;
				List<Picture> cameraPictures = CacheService
						.getTeatcherPictures(mParentContext);
				if (null == cameraPictures || 0 == cameraPictures.size()) {
					homeMediaFolderCamera.mediaPath = "";
					homeMediaFolderCamera.defaultImage = R.drawable.ic_default_album;
				} else {
					homeMediaFolderCamera.mediaPath = cameraPictures.get(0)
							.getPicturePath();
				}
				tempHomeMediaFolders.add(homeMediaFolderCamera);
				homeMediaFolderCamera.pictureList = cameraPictures;

				HomeMediaFolder homeMediaFolderVideo = new HomeMediaFolder();
				homeMediaFolderVideo.folder = mVideoDraft;
				List<Picture> videoList = CacheService
						.getTeatcherVideo(mParentContext);
				if (null == videoList || 0 == videoList.size()) {
					homeMediaFolderVideo.mediaPath = "";
					homeMediaFolderVideo.defaultImage = R.drawable.ic_default_video;
				} else {
					homeMediaFolderVideo.mediaPath = videoList.get(0)
							.getPicturePath();
				}
				tempHomeMediaFolders.add(homeMediaFolderVideo);
				homeMediaFolderVideo.pictureList = videoList;

				HandlerPostUI.getHandlerPostUI(new Runnable() {

					@Override
					public void run() {
						if (null != refreshPictureList) {
							refreshPictureList
									.onRefreshPictureList(tempHomeMediaFolders);
						}
					}
				});
			}
		}).start();

	}

	/**
	 * 显示等待对话框
	 * 
	 * @param messageString
	 * @param onDismissListener
	 */
	protected void showWaitDialog(String messageString,
			final OnKeyCancel onKeyCancel) {
		if (null == mCustomWaitDialog) {
			mCustomWaitDialog = new CustomWaitDialog(mParentContext,
					com.android.support.jhf.R.style.CustomWaitDialog);
			mCustomWaitDialog.setCancelable(true);
			mCustomWaitDialog.setCanceledOnTouchOutside(false);
			mCustomWaitDialog.setMessage(messageString);
			mCustomWaitDialog.setOnKeyCancelListener(new OnKeyCancel() {

				@Override
				public void onKeyCancelListener() {
					if (null != onKeyCancel) {
						onKeyCancel.onKeyCancelListener();
					}
					if (null != mCustomWaitDialog) {
						mCustomWaitDialog.cancel();
						mCustomWaitDialog = null;
					}
				}
			});
			mCustomWaitDialog.setOnKeyListener(new OnKeyListener() {

				@Override
				public boolean onKey(DialogInterface arg0, int keyCode,
						KeyEvent arg2) {
					if (keyCode == KeyEvent.KEYCODE_BACK) {
						return true;
					}
					return false;
				}
			});
			mCustomWaitDialog.show();
		}
	}

	protected void hideWaitDialog() {
		if (null != mCustomWaitDialog) {
			mCustomWaitDialog.cancel();
			mCustomWaitDialog = null;
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case 0: {
			// 照片返回
			switch (resultCode) {
			case Activity.RESULT_OK: {
				if (null != data) {
					List<Picture> pictureList = (List<Picture>) data
							.getSerializableExtra("pictureList");
					int flag = data.getIntExtra("flag", 0);
					if (0 == pictureList.size()) {
						HomeMediaFolder homeMediaFolder = mHomeMediaFolders
								.get(flag);
						homeMediaFolder.pictureList.clear();
						if (0 == flag) {
							homeMediaFolder.mediaPath = "";
							homeMediaFolder.folder = mAllPhoto;
							if(0 == pictureList.size()){
								homeMediaFolder.defaultImage = R.drawable.ic_default_album;
							}
							homeMediaFolder.pictureList.addAll(pictureList);
						} else if (1 == flag) {
							homeMediaFolder.mediaPath = mAppShoot;
							homeMediaFolder.mediaPath = "";
							if(0 == pictureList.size()){
								homeMediaFolder.defaultImage = R.drawable.ic_default_album;
							}
							homeMediaFolder.pictureList.addAll(pictureList);
						} else if (2 == flag) {
							homeMediaFolder.mediaPath = mVideoDraft;
							homeMediaFolder.mediaPath = "";
							if(0 == pictureList.size()){
								homeMediaFolder.defaultImage = R.drawable.ic_default_video;
							}
							homeMediaFolder.pictureList.addAll(pictureList);
						}
					} else {
						HomeMediaFolder homeMediaFolder = mHomeMediaFolders
								.get(flag);
						homeMediaFolder.pictureList.clear();
						homeMediaFolder.mediaPath = pictureList.get(0)
								.getPicturePath();
						homeMediaFolder.pictureList.addAll(pictureList);
					}
					mHomeAdapter.notifyDataSetChanged();
				}
				break;
			}
			case Activity.RESULT_CANCELED: {
				break;
			}
			default:
				break;
			}
			break;
		}
		default:
			break;
		}
	}

}
